const uuid = require("node-uuid");
const fs = require('fs');
const path = require('path');
const formidable = require('formidable');
const moment = require('moment');
const Product = require("../models/product");
const Page = require("../models/page");
const ProPic = require("../models/proPic");
const { returnFn } = require("../config/returnFn");

function checkRootLogin(req, res, next) {
    if (!req.session.employee) {
        return returnFn(res, 400, "未登录");
    }
    next();
}

const queryProduct = (req, res) => {

    let product = new Product({
        proName: req.query.proName ? decodeURI(req.query.proName) : '',
        price: req.query.price ? req.query.price : '',
        num: req.query.num ? req.query.num : '',
        brandId: req.query.brandId ? req.query.brandId : ''
    });
    let page = new Page({
        page: req.query.page ? parseInt(req.query.page) : 0,
        size: req.query.pageSize ? parseInt(req.query.pageSize) : 10
    });

    Product.queryProduct(product, page, (err, data) => {
        if (err) return returnFn(res, 503, "数据库异常");

        Product.countProduct((err, result) => {
            if (err) return returnFn(res, 503, "数据库异常");

            if (data.length == 0) {
                page.count = result.count;
                page.data = data;
                return res.send(page);
            }
            let idStr = "";
            for (let i = 0; i < data.length; i++) {
                if (i == 0) {
                    idStr += data[i].id;
                } else {
                    idStr += "," + data[i].id;
                }
                data[i].pic = new Array();
            }
            ProPic.queryPic(idStr, (err, picData) => {
                if (err) return returnFn(res, 503, "数据库异常");

                for (let l = 0; l < picData.length; l++) {
                    for (let n = 0; n < data.length; n++) {
                        if (data[n].id == picData[l].productId) {
                            data[n].pic[data[n].pic.length] = picData[l];
                        }
                    }
                }
                page.count = result.count;
                page.data = data;
                res.send(page);
            })
        })
    })

}
const queryProductDetail = (req, res) => {
    Product.queryProductDetail(req.query.id, (err, data) => {
        if (err) return returnFn(res, 503, "数据库异常");

        data.pic = new Array();
        ProPic.queryPic(req.query.id, (err, picData) => {
            if (err) return returnFn(res, 503, "数据库异常");

            if (picData && picData.length) {
                data.pic = picData;
            }
            res.send(data);
        })
    })
}
const queryProductDetailList = (req, res) => {
    let product = new Product({
        proName: req.query.proName ? req.query.proName : "",
        price: req.query.price ? req.query.price : "",
        num: req.query.num ? req.query.num : "",
        brandId: req.query.brandId ? req.query.brandId : "",
    });
    let page = new Page({
        page: req.query.page ? parseInt(req.query.page) : 1,
        size: req.query.pageSize ? parseInt(req.query.pageSize) : 10
    });
    Product.queryProductDetailList(product, page, (err1, rows) => {
        if (err1) return returnFn(res, 503, "数据库异常");
        
        Product.countProductDetailList((err2, result) => {
            if (err2) return returnFn(res, 503, "数据库异常");
            
            page.total = result.count;
            page.data = rows;
            returnFn(res, 200, "success", page);
        })
    })
}
const addProductPic = (req, res) => {
    // 创建表单上传
    let form = new formidable.IncomingForm();
    // 设置编辑
    form.encoding = "utf-8";
    // 设置文件存储路径
    form.uploadDir = "public/upload/product";
    // 保留后缀
    form.keepExtensions = true;
    // 设置单文件大小限制 2m
    form.maxFieldsSize = 2 * 2014 * 2014;
    // form.maxFields = 1000;  设置所以文件的大小总和
    form.parse(req, (err, fields, files) => {

        // 最多可上传 3 张图片
        for (let i = 1; i < 4; i++) {
            let file = files['pic' + i];
            if (!file || file.name == "") break;
            let picName = uuid.v1() + path.extname(file.name);
            fs.rename(file.path, "public\\upload\\product\\" + picName, (err) => {
                if (err) return returnFn(res, 502, "图片保存异常");

                let data = {
                    picName,
                    picAddr: "/upload/product/" + picName
                }
                returnFn(res, 200, "success", data);
            })
        }
    })
}
const addPic = (picName, picAddr, productId) => {
    ProPic.addPic({
        picName,
        picAddr,
        productId
    }, (err, data) => {
        console.log("加入一张图片成功");
    })
}
const addProduct = (req, res) => {
    let product = new Product({
        proName: req.body.proName ? req.body.proName : '',
        oldPrice: req.body.oldPrice ? parseFloat(req.body.oldPrice) : '',
        price: req.body.price ? parseFloat(req.body.price) : '',
        proDesc: req.body.proDesc ? req.body.proDesc : '',
        size: req.body.size ? req.body.size : '',
        statu: req.body.statu ? parseInt(req.body.statu) : 1,
        updateTime: moment().format("YYYY-MM-DD HH:mm:ss"),
        num: req.body.num ? parseInt(req.body.num) : '',
        brandId: req.body.brandId ? parseInt(req.body.brandId) : ''
    });
    Product.addProduct(product, (err, result) => {
        if (err) return returnFn(res, 503, "数据库异常");

        if (req.body.picName1 && req.body.picAddr1) {
            addPic(req.body.picName1, req.body.picAddr1, data.insertId);
        }
        if (req.body.picName2 && req.body.picAddr2) {
            addPic(req.body.picName2, req.body.picAddr2, data.insertId);
        }
        if (req.body.picName3 && req.body.picAddr3) {
            addPic(req.body.picName3, req.body.picAddr3, data.insertId);
        }
        returnFn(res, 200, "success", result);
    })
}
const updateProduct = (req, res) => {
    let product = new Product({
        id: req.body.id ? parseInt(req.body.id) : '',
        proName: req.body.proName ? req.body.proName : '',
        oldPrice: req.body.oldPrice ? parseFloat(req.body.oldPrice) : '',
        price: req.body.price ? parseFloat(req.body.price) : '',
        proDesc: req.body.proDesc ? req.body.proDesc : '',
        size: req.body.size ? req.body.size : '',
        statu: req.body.statu ? parseInt(req.body.statu) : '',
        updateTime: moment().format("YYYY-MM-DD HH:mm:ss"),
        num: req.body.num ? parseInt(req.body.num) : '',
        brandId: req.body.brandId ? parseInt(req.body.brandId) : ''
    })
    Product.updateProduct(product, (err, data) => {
        if (err) return returnFn(res, 503, "数据库异常！");

        ProPic.delPic(req.body.id, (err, picData) => {
            if (err) return returnFn(res, 503, "数据库异常！");
            
            if (req.body.picName1 && req.body.picAddr1) {
                addPic(req.body.picName1, req.body.picAddr1, req.body.id);
            }
            if (req.body.picName2 && req.body.picAddr2) {
                addPic(req.body.picName2, req.body.picAddr2, req.body.id);
            }
            if (req.body.picName3 && req.body.picAddr3) {
                addPic(req.body.picName3, req.body.picAddr3, req.body.id);
            }

            returnFn(res, 200, "success", { data, picData });
        })
    });
}

module.exports = {
    checkRootLogin,
    queryProduct,
    queryProductDetail,
    queryProductDetailList,
    addProduct,
    addProductPic,
    updateProduct
}